package com.lanyan.system.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.lanyan.common.utils.DateUtils;
import com.lanyan.common.utils.http.HttpUtils;
import com.lanyan.common.utils.wx.WxAppletUserInfo;
import com.lanyan.system.domain.*;
import com.lanyan.system.domain.vo.OrdersItemVo;
import com.lanyan.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.lanyan.common.utils.StringUtils;
import com.lanyan.system.mapper.OrdersMapper;
import com.lanyan.system.domain.vo.OrdersVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 订单Service业务层处理
 *
 * @author lanyan
 * @date 2024-11-26
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ICourierService courierService;
    @Autowired
    private IEstateService estateService;
    @Autowired
    private IBuildingService buildingService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询订单
     *
     * @param ordersId 订单主键
     * @return 订单
     */
    @Override
    public Orders selectOrdersByOrdersId(Long ordersId) {
        return this.getById(ordersId);
    }

    /**
     * 查询订单Vo列表
     *
     * @param orders 订单
     * @return 订单
     */
    @Override
    public List<OrdersVo> selectOrdersVoList(Orders orders) {
        return selectOrdersList(orders)
                .stream()
                .map(x -> (OrdersVo) x)
                .collect(Collectors.toList());
    }

    /**
     * 查询订单列表
     *
     * @param orders 订单
     * @return 订单
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders) {
        LambdaQueryChainWrapper<Orders> wrapper = this.lambdaQuery().eq(Orders::getDelFlag, "0");
        if (StringUtils.isNotEmpty(orders.getType())) {
            wrapper.eq(Orders::getType, orders.getType());
        }
        if (StringUtils.isNotEmpty(orders.getSecondType())) {
            wrapper.eq(Orders::getSecondType, orders.getSecondType());
        }
        if (orders.getCourierId() != null) {
            wrapper.eq(Orders::getCourierId, orders.getCourierId());
        }
        if (orders.getAccountId() != null) {
            wrapper.eq(Orders::getAccountId, orders.getAccountId());
        }
        if (StringUtils.isNotEmpty(orders.getFetchName())) {
            wrapper.like(Orders::getFetchName, orders.getFetchName());
        }
        if (StringUtils.isNotEmpty(orders.getFetchPhone())) {
            wrapper.eq(Orders::getFetchPhone, orders.getFetchPhone());
        }
        if (StringUtils.isNotEmpty(orders.getFetchBuilding())) {
            wrapper.eq(Orders::getFetchBuilding, orders.getFetchBuilding());
        }
        if (StringUtils.isNotEmpty(orders.getFetchDetails())) {
            wrapper.eq(Orders::getFetchDetails, orders.getFetchDetails());
        }
        if (StringUtils.isNotEmpty(orders.getSendName())) {
            wrapper.like(Orders::getSendName, orders.getSendName());
        }
        if (StringUtils.isNotEmpty(orders.getSendPhone())) {
            wrapper.eq(Orders::getSendPhone, orders.getSendPhone());
        }
        if (StringUtils.isNotEmpty(orders.getSendBuilding())) {
            wrapper.eq(Orders::getSendBuilding, orders.getSendBuilding());
        }
        if (StringUtils.isNotEmpty(orders.getSendDetails())) {
            wrapper.eq(Orders::getSendDetails, orders.getSendDetails());
        }
        if (StringUtils.isNotEmpty(orders.getMemo())) {
            wrapper.eq(Orders::getMemo, orders.getMemo());
        }
        if (StringUtils.isNotEmpty(orders.getSpecialMemo())) {
            wrapper.eq(Orders::getSpecialMemo, orders.getSpecialMemo());
        }
        if (StringUtils.isNotEmpty(orders.getSpecialMemoImg())) {
            wrapper.eq(Orders::getSpecialMemoImg, orders.getSpecialMemoImg());
        }
        if (StringUtils.isNotEmpty(orders.getProductType())) {
            wrapper.eq(Orders::getProductType, orders.getProductType());
        }
        if (orders.getWeight() != null) {
            wrapper.eq(Orders::getWeight, orders.getWeight());
        }
        if (orders.getReceivingTime() != null) {
            wrapper.eq(Orders::getReceivingTime, orders.getReceivingTime());
        }
        if (orders.getMoney() != null) {
            wrapper.eq(Orders::getMoney, orders.getMoney());
        }
        if (orders.getOriginMoney() != null) {
            wrapper.eq(Orders::getOriginMoney, orders.getOriginMoney());
        }
        if (StringUtils.isNotEmpty(orders.getState())) {
            wrapper.eq(Orders::getState, orders.getState());
        }
        if (StringUtils.isNotEmpty(orders.getOrdersNo())) {
            wrapper.eq(Orders::getOrdersNo, orders.getOrdersNo());
        }
        if (StringUtils.isNotEmpty(orders.getPayNo())) {
            wrapper.eq(Orders::getPayNo, orders.getPayNo());
        }
        if (StringUtils.isNotEmpty(orders.getCode())) {
            wrapper.eq(Orders::getCode, orders.getCode());
        }
        if (StringUtils.isNotEmpty(orders.getStartTime())) {
            wrapper.between(Orders::getCreateTime, orders.getStartTime(), orders.getEndTime());
        }
        if (StringUtils.isNotEmpty(orders.getDay())) {
            wrapper.between(Orders::getDay, StringUtils.format("{} 00:00:00", orders.getDay()), StringUtils.format("{} 23:59:59", orders.getDay()));
        }
        if (orders.getCouponId() != null) {
            wrapper.eq(Orders::getCouponId, orders.getCouponId());
        }
        if (StringUtils.isNotEmpty(orders.getTimeType())) {
            LocalDate today = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00");
            switch (orders.getTimeType()) {
                case "0":
                    wrapper.gt(OrdersVo::getReceivingTime, today.format(formatter));
                    break;
                case "1":
                    LocalDate startOfWeek = today.with(ChronoField.DAY_OF_WEEK, 1);
                    wrapper.gt(OrdersVo::getReceivingTime, startOfWeek.format(formatter));
                    break;
                case "2":
                    LocalDate startOfMonth = today.withDayOfMonth(1);
                    wrapper.gt(OrdersVo::getReceivingTime, startOfMonth.format(formatter));
                    break;
            }
        }
        return wrapper.list();
    }

    /**
     * 新增订单
     *
     * @param orders 订单
     * @return 结果
     */
    @Override
    public boolean insertOrders(Orders orders) {
        orders.setCreateTime(DateUtils.getNowDate());
        return this.save(orders);
    }

    /**
     * 修改订单
     *
     * @param orders 订单
     * @return 结果
     */
    @Override
    public boolean updateOrders(Orders orders) {
        orders.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(orders);
    }

    /**
     * 批量删除订单
     *
     * @param ordersIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public boolean deleteOrdersByOrdersIds(Long[] ordersIds) {
        return this.lambdaUpdate().set(Orders::getDelFlag, "1").in(Orders::getOrdersId, ordersIds).update();
    }

    /**
     * 删除订单信息
     *
     * @param ordersId 订单主键
     * @return 结果
     */
    @Override
    public boolean deleteOrdersByOrdersId(Long ordersId) {
        return this.lambdaUpdate().set(Orders::getDelFlag, "1").eq(Orders::getOrdersId, ordersId).update();
    }

    @Override
    public void sendWx(long ordersId) {

        //https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/sendMessage.html
        String token = WxAppletUserInfo.getMPToken(
                configService.selectConfigByKey("wx.ps.appId"),
                configService.selectConfigByKey("wx.ps.secret")
        );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());
        Orders orders = this.getById(ordersId);
        Building building = buildingService.getById(orders.getSendBuilding());
        Courier courier = courierService.getById(building.getCourierId());

        if (courier != null && StringUtils.isNotEmpty(courier.getOpenId())){
            Estate estate = estateService.getById(building.getEstateId());
            JSONObject params = new JSONObject();
            params.put("access_token", token);
            params.put("template_id", "HQ4lLIvbYkpRL7hu8Po9gG-1UfmIZ4w502w_QxSBN4w");
            params.put("touser", courier.getOpenId());
            JSONObject data = new JSONObject();
            data.put("character_string3", setData(orders.getOrdersNo()));
            data.put("thing2", setData(StringUtils.equals(orders.getType(),"0") ? "商城订单" : "配送订单"));
            data.put("thing1", setData(estate.getName() + building.getName() + orders.getSendDetails()));
            params.put("data", data);
            params.put("page", "/pages/order/order_detail?id=" + orders.getOrdersId() + "&tid=1");
            params.put("miniprogram_state", "formal");
            params.put("lang", "zh_CN");
            HttpUtils.sendPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token, params.toJSONString());
        }
    }

        public JSONObject setData(Object value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("value", value);
        return jsonObject;
    }
}
